from app.dongcai.apis import get_dates
from app.dongcai.mongo_cols import stocks_col
from config import settings


class History(object):
    def __init__(self):
        self._dates = []
        self.data = {}
        # self.update()

    def init_data(self, date: str):
        for item in stocks_col.find({'date': date}):
            if self.data.get(item['symbol']):
                self.data[item['symbol']].update({date: item})
            else:
                self.data[item['symbol']] = {date: item}
        self._dates.append(date)

    def update(self):
        if settings.get("env") == "test":
            return None
        for date in get_dates(30):
            if date not in self._dates:
                self.init_data(date)

    def get_data(self, symbol):
        results = []
        if self.data.get(symbol):
            for _, i in self.data[symbol].items():
                results.append(i)
        return sorted(results, key=lambda k: k['date'], reverse=True)


history = History()
